package com.neuedu.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.neuedu.dao.CartDAO;
import com.neuedu.entity.Cart;
import com.neuedu.utils.DruidDataSourceUtil;

public class CartDAOImpl implements CartDAO {

	@Override
	public int updatecart(Cart cart) {
		
		Cart c=checkByid(cart.getGid(), cart.getUid());
		int i=-1;
		if(c==null) {
			i=insert(cart);
		}else {
		   cart.setGnumber(c.getGnumber()+cart.getGnumber());
		   i=update(cart);
		}
		
		
		
		return i;
	}

	@Override
	public int insert(Cart cart) {
		Connection conn=null;
		PreparedStatement pstm=null;
		int i=-1;
		try {
		conn=DruidDataSourceUtil.getConnection();
		
		String sql="insert into t_cart(gid,uid,gnumber) values(?,?,?)";
		
			pstm=conn.prepareStatement(sql);
			
			pstm.setObject(1, cart.getGid());
			pstm.setObject(2, cart.getUid());
			pstm.setObject(3, cart.getGnumber());
			
			i=pstm.executeUpdate();
			
			
		} catch (SQLException e) {
		
			e.printStackTrace();
		}finally {
			try {
				conn.close();
				pstm.close();
			}catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
		return i;
	}

	@Override
	public int update(Cart cart) {
		Connection conn=null;
		PreparedStatement pstm=null;
		int i=-1;
		try {
		conn=DruidDataSourceUtil.getConnection();
		
		String sql="update t_cart set gnumber=? where uid=? and gid=?";
		
			pstm=conn.prepareStatement(sql);
			
			pstm.setObject(3, cart.getGid());
			pstm.setObject(2, cart.getUid());
			pstm.setObject(1, cart.getGnumber());
			
			i=pstm.executeUpdate();
			
			
		} catch (SQLException e) {
		
			e.printStackTrace();
		}finally {
			try {
				conn.close();
				pstm.close();
			}catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
		return i;
	}

	@Override
	public Cart checkByid(Integer gid, Integer uid) {
		Connection conn=null;
		PreparedStatement pstm=null;
		ResultSet rs=null;
		Cart cart=new Cart();
		try {
		conn=DruidDataSourceUtil.getConnection();
		
		String sql="select * from t_cart where uid=? and gid=?";
		
			pstm=conn.prepareStatement(sql);
			
			pstm.setObject(2, gid);
			pstm.setObject(1, uid);
		
			
			rs=pstm.executeQuery();
			while(rs.next()) {
				cart.setCid(rs.getInt("cid"));
				cart.setGid(rs.getInt("gid"));
				cart.setUid(rs.getInt("uid"));
				cart.setGnumber(rs.getInt("gnumber"));
			}
			
			
		} catch (SQLException e) {
		
			e.printStackTrace();
		}finally {
			try {
				conn.close();
				pstm.close();
				rs.close();
			}catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(cart.getCid()==null||cart.getGid()==null||cart.getUid()==null) {
			return null;
		}
		return cart;
	}
   
}
